import time
from selenium.webdriver import ChromeOptions
from selenium.webdriver import Chrome
# 【2】驱动位置服务
from selenium.webdriver.chrome.service import Service
# 【3】选择器
from selenium.webdriver.common.by import By
from fake_useragent import UserAgent

# 【二】创建浏览器对象
# 【1】指定驱动位置
executable_path = "./chromedriver.exe"
service = Service(executable_path=executable_path)
options = ChromeOptions()
# 无痕模式
options.add_argument('--incognito')  # 隐身模式（无痕模式）
# 禁用浏览器自动化提示条
options.add_argument('--disable-blink-features=AutomationControlled')
# 排除启用自动化开关
options.add_experimental_option("excludeSwitches", ["enable-automation"])
# 关闭自动化扩展信息
options.add_experimental_option('useAutomationExtension', False)
# 设置Chrome为正常用户模式
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')

# 设置Agent
options.add_argument(
    f'--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0')
# 【2】创建浏览器对象
browser = Chrome(service=service, options=options)
# 设置隐式等待时间为10秒
browser.implicitly_wait(10)
# 关键：执行CDP命令来隐藏webdriver属性，避免被检测
browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
        Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
        })
    """
})
# ========== 第一步：先访问京东网站，建立域名连接 ==========
print("正在访问京东首页...")
browser.get("https://www.jd.com")
time.sleep(2)  # 等待页面加载
print("京东首页访问成功！")

# ========== 第二步：准备cookie字符串 ==========
# 获取cookie的方法：
# 1. 手动登录京东后，在浏览器控制台执行: document.cookie
# 2. 或者使用 browser.get_cookies() 获取登录后的cookie并保存
cookie_str = "shshshfpa=b2f350ea-1478-08fc-d667-fd541dc18e3e-1744895988; shshshfpx=b2f350ea-1478-08fc-d667-fd541dc18e3e-1744895988; 3AB9D23F7A4B3C9B=UWF2IHN27IG2TLFHQNKPJCVREDZO3NSSGB62AQ4ABE7QY6PXRISFO6LETMVB5NRQJSJLQBAG46RPQVQOUAEIGZVNBQ; __jdv=76161171|direct|-|none|-|1761725476708; __jdu=17617254767081815778821; 3AB9D23F7A4B3CSS=jdd03UWF2IHN27IG2TLFHQNKPJCVREDZO3NSSGB62AQ4ABE7QY6PXRISFO6LETMVB5NRQJSJLQBAG46RPQVQOUAEIGZVNBQAAAAM2F4CXLEQAAAAADOE3TWWS47UU3YX; _gia_d=1; o2State={%22webp%22:true%2C%22avif%22:true}; areaId=18; ipLoc-djd=18-1495-0-0; TrackID=1SibBoTS2V3EUtTgB0GSc_f1SFs75NtjwgggeonFMsatySghHxf-xMl-GsF4Z4EFv287hFci3JcSQM0S79QrKOA4i5LCxirM67qVKC_vRmEc; thor=67D805C4A5DFBBD668231D7E16873FF9A3D183140753B2D84EE3579CB40003C6A983A014EE37D9167630639C12EA81B3BE5088275B64FDA8BF6464ADB55AADA45156D08167D047BEA3FF9EEC19EB223F240348274271249BA345BC58364D81996E4FC51918DD81A6D5432FA48D35BB5EC751227F7B4E52AACE4D9B017ED5C18DC203ECA2D64A0E6058937C60EDCCF891985B4577066C6139C4465EA6DB3C2ACD; flash=3_CoGZPUseOoeXvXW5XCon6SYR6_pw6OWQY0dTwlh62zo8Hou3mYZFDSNr8ezOorZs8D8gY_kLEvSAhcjLfO3DCmKcpT6BmBxZzC9sB86kh3k5eddiQbsNwEz1Gs_WrXX8dgUUPjExPsqKjDY3O7uLjOTgucwGzSrGpG61LCIUGIp1HlnMDWa0; light_key=AASBKE7rOxgWQziEhC_QY6yackTbA_Qruyru4raHwZ-Lo2qxJS5aaDQfWgp5lrv4ADhruij2; pinId=MqL3tzF-IoBilT8DU8FzEw; pin=jd_UQDjyQZAQHtr; unick=jd_2x2gu82rac9gfw; ceshi3.com=000; _tp=7fmgl0tEjrG6P9P%2FcjYNwQ%3D%3D; _pst=jd_UQDjyQZAQHtr; wlfstk_smdl=v1sfxorzi9n71jqgzm3k6sumv2n83vez; __jda=76161171.17617254767081815778821.1761725477.1761725477.1761725477.1; __jdc=76161171; cn=11; UseCorpPin=jd_UQDjyQZAQHtr; __jdb=76161171.5.17617254767081815778821|1.1761725477; sdtoken=AAbEsBpEIOVjqTAKCQtvQu178oSND8NR4Pxsrml-7qArsMo1b1Cv2Jjv1nIAhnj9OYKeMR-cYjGksHCmwmgwCD8MKScXJTR0KRIaFEDQSDIkb5ulsQGAFqByz0lFv_DJrUdKBkUaVik; shshshfpb=BApXW6-0OLP9ABf765j_mSGSulCOmBz_kBgbIXqdp9xJ1PdZfQrPnthDyvRHbAq5nYSbH1qnnjzlTlA"

# ========== 第三步：解析并添加cookie ==========
print("开始添加cookie...")
cookies_dict = {}
for cookie_item in cookie_str.split(";"):
    cookie_item = cookie_item.strip()
    if "=" in cookie_item:
        # 只分割第一个=号,防止cookie值中的=号被误分割
        name, value = cookie_item.split("=", 1)
        cookies_dict[name] = value

# 添加cookie到浏览器（必须在访问网站后才能添加）
success_count = 0
fail_count = 0
for name, value in cookies_dict.items():
    try:
        browser.add_cookie({
            "name": name,
            "value": value,
            "domain": ".jd.com",  # 指定域名，确保cookie能正确设置
            "path": "/"
        })
        success_count += 1
    except Exception as e:
        print(f"❌ 添加cookie失败: {name}, 错误: {e}")
        fail_count += 1

print(f"✅ Cookie添加完成！成功: {success_count} 个, 失败: {fail_count} 个")

# ========== 第四步：刷新页面让cookie生效 ==========
print("刷新页面以应用cookie...")
browser.refresh()
time.sleep(3)

# ========== 第五步：验证是否登录成功 ==========
# 检查页面上是否有登录用户名
try:
    # 京东登录后会在右上角显示用户名
    username_element = browser.find_element(By.CLASS_NAME, "nickname")
    username = username_element.text
    print(f"🎉 登录成功！当前用户: {username}")
except:
    print("⚠️  未检测到登录状态，cookie可能已过期或无效")
    print("建议重新获取最新的cookie")

# 搜索手机
search_input = browser.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[1]/div[2]/div[2]/div[2]/input")
search_input.send_keys("手机")
time.sleep(2)
search_but = browser.find_element(By.XPATH, "/html/body/div[1]/div[5]/div[1]/div[2]/div[2]/div[2]/button")
search_but.click()
print("等待加载。。。。。。")
time.sleep(10)
# 获取商品列表
goods_list = browser.find_elements(By.XPATH, "/html/body/div[2]/div[3]/div/div/div/div[2]/div[1]")
for goods in goods_list:
    goods_img = goods.find_element(By.XPATH, "./div[1]/div/div[1]/img").get_attribute("src")
    goods_name = goods.find_element(By.XPATH, "./div[1]/div/div[2]/div/div[1]/span").get_attribute("title")
    goods_tags_div = goods.find_element(By.XPATH, "./div[1]/div/div[2]/div/div[2]")

    # 提取div中所有span的文字，存入列表（忽略i标签中的文字）
    goods_tags_list = []
    try:
        # 查找所有span元素
        span_elements = goods_tags_div.find_elements(By.TAG_NAME, "span")
        for span in span_elements:
            # 获取span的完整文本
            full_text = span.text.strip()

            # 获取span下所有i标签的文本
            i_elements = span.find_elements(By.TAG_NAME, "i")
            i_texts = [i.text.strip() for i in i_elements]

            # 从完整文本中移除i标签的文本
            clean_text = full_text
            for i_text in i_texts:
                if i_text:
                    clean_text = clean_text.replace(i_text, "").strip()

            # 添加到列表（只添加非空文本）
            if clean_text:
                goods_tags_list.append(clean_text)
    except Exception as e:
        print(f"提取标签失败: {e}")

    goods_price_span = goods.find_element(By.XPATH, "./div[1]/div/div[2]/div/div[3]/span")
    # span中的li标签忽略
    goods_price = goods_price_span.text.strip()

    # 打印提取的信息
    print(f"商品名称: {goods_name}")
    print(f"商品图片: {goods_img}")
    print(f"商品标签: {goods_tags_list}")
    print(f"商品价格: {goods_price}")
    print("-" * 50)

